﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;

public partial class AssignToEN : System.Web.UI.Page
{

    public Persons reqPersons
    {
        get
        {
            if (ViewState["reqPersons"] == null)
                ViewState["reqPersons"] = System.Guid.NewGuid().ToString();
            return Session[ViewState["reqPersons"].ToString()] as Persons;
        }
        set
        {
            if (ViewState["reqPersons"] == null)
                ViewState["reqPersons"] = System.Guid.NewGuid().ToString();
            Session[ViewState["reqPersons"].ToString()] = value;
        }
    }



    public Persons mobjPersons
    {
        get
        {
            if (ViewState["mobjPersons"] == null)
                ViewState["mobjPersons"] = System.Guid.NewGuid().ToString();
            return Session[ViewState["mobjPersons"].ToString()] as Persons;
        }
        set
        {
            if (ViewState["mobjPersons"] == null)
                ViewState["mobjPersons"] = System.Guid.NewGuid().ToString();
            Session[ViewState["mobjPersons"].ToString()] = value;
        }
    }


    protected List<Persons> _lstReqPerosns
    {
        get
        {
            if (ViewState["_lstReqPerosns"] == null)
                ViewState["_lstReqPerosns"] = System.Guid.NewGuid().ToString();
            return Session[ViewState["_lstReqPerosns"].ToString()] as List<Persons>;
        }

        set
        {
             
            if (ViewState["_lstReqPerosns"] == null)
                ViewState["_lstReqPerosns"] = System.Guid.NewGuid().ToString();
            Session[ViewState["_lstReqPerosns"].ToString()] = value;
       
        }
    }



    public List<Persons> lstReqPersons
    {
        get
        {
            if (_lstReqPerosns == null)
            {
                if (Request["randid"] == null)
                    return new List<Persons> ();

                string strPageID = Request["randid"].ToString();

                if (Session[strPageID] == null)
                    return new List<Persons> ();

                _lstReqPerosns = Session[strPageID] as List<Persons>;

                Session.Remove(strPageID);

            }

            return _lstReqPerosns;
        }
    }



    public List<Persons> lstGridPersons
    {
        get
        {
            if (ViewState["lstGridPersons"] == null)
            {
                ViewState["lstGridPersons"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["lstGridPersons"].ToString()] == null)
            {
                Session[ViewState["lstGridPersons"].ToString()] = new List<Persons>();

            }

            return (List<Persons>)Session[ViewState["lstGridPersons"].ToString()];

        }
        set
        {
            if (ViewState["lstGridPersons"] == null)
            {
                ViewState["lstGridPersons"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["lstGridPersons"].ToString()] = value;
        }  



    }



    protected void Page_Load(object sender, EventArgs e)
    {
        Persons objPersons = GlobalVars.getCurrentPerson();

        mobjPersons = objPersons;

        checkSecurityAndCustomizePage(objPersons);

        checkID();

        bindAllControls();

    }


    /// <summary>
    /// this function will bind controls with employee values
    /// </summary>
    private void bindAllControls()
    {
        //lblReqEmployeeBadge.Text = reqPersons.Badge.ToString();
        //lblReqEmployeeName.Text = reqPersons.Name_EN + " " + reqPersons.MiddleName_EN + " " + reqPersons.FamilyName_EN;

    }

    /// <summary>
    /// this function will bind the employees grid
    /// </summary>
    private void bindEmployeesGrid()
    {
        grdEmployees.DataSource = lstReqPersons;
        grdEmployees.DataBind();
    }


    /// <summary>
    /// this function will check for ID in Request and if it's belong to current employee
    /// </summary>
    protected void checkID()
    {
       


        long reqID = 0;

        try { reqID = long.Parse(Request["ID"]); }
        catch {

            if (lstReqPersons.Count == 0)
                Response.Redirect("LoginEN.aspx");


            bindEmployeesGrid();

            return;
        }

        PersonsDB objPersonsDB = new PersonsDB (ConnectionStrings.LMS);

        List<Persons> lstTemp = objPersonsDB.getPersonsByGenID(reqID);

        if (lstTemp.Count == 0)
            Response.Redirect("LoginEN.aspx");


        reqPersons = lstTemp[0];


        _lstReqPerosns = new List<Persons>();

        _lstReqPerosns.Add(reqPersons);

        if (!mobjPersons.lstAllEmployees.Contains(reqPersons))
            Response.Redirect("LoginEN.aspx");


        bindEmployeesGrid();
    }



    /// <summary>
    /// this function will bind the grid with the persons
    /// </summary>
    protected void bindGrid()
    {

        mobjPersons.clearchilds();
        List<Persons> lstPersons =   mobjPersons.lstAllEmployees;

        lstGridPersons = lstPersons;
        grdUsers.DataSource = lstPersons;
        grdUsers.DataBind();
    }



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check



        if ((!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Manager_page)) && currentPerson.lstAddEmployees.Count == 0)
            Response.Redirect("LoginEN.aspx");




    }
    
   




    




    


   

   
    
    
    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = lstGridPersons;
        grdUsers.PageIndex = e.NewPageIndex;
        grdUsers.DataBind();

    }
    
    
    
    
    
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        lstGridPersons = search(txtSearch.Text);

        grdUsers.DataSource = lstGridPersons;
        grdUsers.DataBind();

    }



    /// <summary>
    /// this function will search in Persons and return the values
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of Persons  matched</returns>
    protected List<Persons> search(string txtText)
    {

        PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);
        List<Persons> lstRet = new List<Persons>();

        if (txtText.Trim() == "")
        {
            List<Persons> lstNew = objPersonsDB.Select(" top 100 ", " where ID = '' order by [Name_EN] ");
            //lstNew = new List<Persons>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
            return lstNew;
        }


        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }



        foreach (string strValue in strValues)
        {
            Persons objPersons = new Persons();
            objPersons.Badge = objPersons.ID = objPersons.FamilyName_AR = objPersons.FamilyName_EN = objPersons.Name_AR = objPersons.Name_EN =
                objPersons.MiddleName_AR = objPersons.MiddleName_EN = "%" + strValue + "%";
            

            List<Persons> lstPersons = objPersonsDB.SearchLikeOROrderByNAME_EN(objPersons);
            lstPersons = new List<Persons>(from objFol in lstPersons where objFol.ID == "" select objFol);

            foreach (Persons objFol in lstPersons)
            {
                if (((from objIn in lstRet where objIn.GenID == objFol.GenID select objIn).ToList().Count == 0) && objFol.lstAllRulesIDs.Contains((long)RulesEnum.Manager_page))
                {
                    lstRet.Add(objFol);
                }
            }

        }


        return lstRet;



    }


    protected void grdUsers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        long editedID = long.Parse(grdUsers.DataKeys[e.NewEditIndex]["GenID"].ToString());

        ManagerEmployees me = new ManagerEmployees();
       

                

        ManagerEmployeesDB objManagerEmployeesDB = new ManagerEmployeesDB(ConnectionStrings.LMS);

        List<ManagerEmployees> lstTest = objManagerEmployeesDB.Search(me);

        foreach (Persons req in lstReqPersons)
        {
            me = new ManagerEmployees();
            me.EmployeeID = req.GenID;
            me.ManagerID = editedID;

            objManagerEmployeesDB.Insert(me);
           
        }



        lblResult.Text = "The Selected Employees delegated to the new manager.";

        string strTitle = "Employee Delegated by you";
        string strMessage = "You delegated Employees to Manager : " + me.objManager.getFullName() + " in \"iLearn\" system .";
        string MailAddress = mobjPersons.Email;

        GlobalVars.SendRequestMail(strTitle, GlobalVars.buildMailBody(strMessage, false), MailAddress);


        strTitle = "Employees Delegated to you";
        strMessage = "Employees was Delegated to you by manager : " + mobjPersons.getFullName() + " in \"iLearn\" system .";
        MailAddress = me.objManager.Email;

        GlobalVars.SendRequestMail(strTitle, GlobalVars.buildMailBody(strMessage, false), MailAddress);

        
        //else
        //{
        //    objManagerEmployeesDB.Delete(lstTest[0]);
        //    lblResult.Text = "The Employee un assigned from this manager.";



        //    string strTitle = "Employee Undelegated by you";
        //    string strMessage = "You undelegated Employee : " + reqPersons.getFullName() + "  from Manager : " + me.objManager.getFullName() + " in \"iLearn\" system .";
        //    string MailAddress = mobjPersons.Email;

        //    GlobalVars.SendRequestMail(strTitle, GlobalVars.buildMailBody(strMessage, false), MailAddress);


        //    strTitle = "Employee Undelegated from you";
        //    strMessage = "Employee : " + reqPersons.getFullName() + " Undelegated from you by manager : " + mobjPersons.getFullName() + " in \"iLearn\" system .";
        //    MailAddress = me.objManager.Email;

        //    GlobalVars.SendRequestMail(strTitle, GlobalVars.buildMailBody(strMessage, false), MailAddress);


        //}


        grdUsers.DataSource = lstGridPersons;
        grdUsers.DataBind();

        
        
        
    }


    protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            long editedID = long.Parse(grdUsers.DataKeys[e.Row.RowIndex]["GenID"].ToString());

            PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);

            List<Persons> lstManagers = objPersonsDB.getPersonsByGenID(editedID);

            if (lstManagers.Count > 0)
            {

                List<Persons> lstCheck = new List<Persons>(from obj in lstReqPersons where lstManagers[0].lstAllEmployees.Contains(obj) select obj);


                if (lstCheck.Count == lstReqPersons.Count)
                {
                    LinkButton lnkAssign = (LinkButton)e.Row.FindControl("lnkAssign");

                    lnkAssign.Visible = false;

                    
                }


            }
        
        }
    }
    protected void grdEmployees_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdEmployees.DataSource = lstReqPersons;
        grdEmployees.PageIndex = e.NewPageIndex;
        grdEmployees.DataBind();
    }
}
